/**
 * coomix 的公共脚本方法
 */
var coomix = {t:{},p:{},m:{},h:{},tmpl:{},dom:{}};
/**
 * 浏览器检测判断方法
 */
coomix.userAgent = navigator.userAgent.toLowerCase();
coomix.browser = {
	version: (coomix.userAgent.match(/(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
	safari: /webkit/.test(coomix.userAgent) &&  !/chrome/.test(coomix.userAgent),
	chrome: /chrome/.test(coomix.userAgent),
	opera: /opera/.test(coomix.userAgent),
	msie: /msie/.test(coomix.userAgent) && !/opera/.test(coomix.userAgent),
	firefox: /firefox/.test(coomix.userAgent),
	mozilla: /mozilla/.test(coomix.userAgent) && !/(compatible|webkit)/.test(coomix.userAgent),
	maxthon: (window.external && (typeof(window.external.max_version) == "string"))?true:false,
	maxthonVersion: (window.external && (typeof(window.external.max_version) == "string"))?window.external.max_version.substr(0,1):undefined
};

/**
 * 扩展函数功能
 * @param destination 要扩展的函数
 * @param source 扩展函数
 * @example <pre>
 coomix.extend(Array.prototype,{
	clear : function () 
	{
		this.length = 0;
		return this;
	},
	first : function () 
	{
		return this[0];
	}
});
</pre>
 */
coomix.extend = function(destination, source) {
  for (var property in source)
  {
    destination[property] = source[property];
  }
  return destination;
};

/**
 * 遍历节点函数
 */
coomix.closest = function( expr ) {  
    // 如果字符串包含位置伪类或者是个元素节点,则封装为一个dom对象,否则为0(即false的简写,用于快速跳过分支)  
    var node =  expr.nodeType ? expr : 0, nodes = dom.slice(this);//将它转换为纯数组  
    //遍历原dom对象的节点  
    for (var i = 0, ret = [], cur; cur = this[i++];) {//由于肯定里面都是节点,因此可以使用这种循环  
        while (cur && cur.nodeType === 1 ) {  
            //如果是dom对象,则判定其是否包含当前节点,否则使用matchesSelector方法判定这个节点是否匹配给定的表达式expr  
            if ( node ? nodes.indexOf(node) > -1 : matchElement( cur, expr ) ){  
                //indexOf方法在某些浏览器需要自行实现  
                //是则放入选择器中  
                ret.push( cur );  
                break;  
            } else {  
                // 否则把当前节点变为其父节点  
                cur = cur.parentNode;  
            }  
        }  
    }  
    //如果大于1,进行唯一化操作  
    ret = ret.length > 1 ? dom.unique( ret ) : ret;  
    //将节点集合重新包装成一个新dom对象返回  
    return this.labor(ret);  
};

/**
 * 拷贝所有属性到一个对象中.
 * @param obj 接受的对象
 * @param source 源对象
 * @param defaults 其他配置项
 * @return obj 返回对象
 * @member apply
 */
coomix.apply = function(obj, source, defaults){
    if(defaults){
    	coomix.apply(obj,defaults);
    }
    if(obj && source && typeof source == 'object'){
        for(var p in source){
        	obj[p] = source[p];
        }
    }
    return obj;
};

/**
 * ext里面抽取出来的常用方法
 */
(function(){
	var idSeed = 0,
        toString = Object.prototype.toString,//字符串
        isIterable = function(v){//是否为迭代类型 如数组 列表类型的集合 
            //check for array or arguments
            if(coomix.isArray(v) || v.callee){
                return true;
            }
            //check for node list type
            if(/NodeList|HTMLCollection/.test(toString.call(v))){
                return true;
            }
            //NodeList has an item and length property
            //IXMLDOMNodeList has nextNode method, needs to be checked first.
            return ((v.nextNode || v.item) && coomix.isNumber(v.length));
        },
		ua = navigator.userAgent.toLowerCase(),//浏览器信息
        check = function(r){
            return r.test(ua);
        },
		DOC = document,
        isStrict = DOC.compatMode == "CSS1Compat",
        isOpera = check(/opera/),
        isChrome = check(/chrome/),
        isWebKit = check(/webkit/),
        isSafari = !isChrome && check(/safari/),
        isSafari2 = isSafari && check(/applewebkit\/4/),
        isSafari3 = isSafari && check(/version\/3/),
        isSafari4 = isSafari && check(/version\/4/),
        isIE = !isOpera && check(/msie/),
        isIE7 = isIE && check(/msie 7/),
        isIE8 = isIE && check(/msie 8/),
        isIE6 = isIE && !isIE7 && !isIE8,
        isGecko = !isWebKit && check(/gecko/),
        isGecko2 = isGecko && check(/rv:1\.8/),
        isGecko3 = isGecko && check(/rv:1\.9/),
        isBorderBox = isIE && !isStrict,
        isWindows = check(/windows|win32/),
        isMac = check(/macintosh|mac os x/),
        isAir = check(/adobeair/),
        isLinux = check(/linux/),
        isSecure = /^https/i.test(window.location.protocol);
    // remove css image flicker
    if(isIE6){
        try{
            DOC.execCommand("BackgroundImageCache", false, true);
        }catch(e){}
    }
	coomix.apply(coomix, {
		//客户端基本属性判断
        isStrict : isStrict,
        /**
         * True 表示为加密SSL协议
         */
        isSecure : isSecure,
        /**
         * True 当文档加载完成
         */
        isReady : false,
		/**
		 * 判断浏览器类型
		 */
        isOpera : isOpera,
        isWebKit: isWebKit,
        isChrome : isChrome,
        isSafari : isSafari,
        isSafari3 : isSafari3,
        isSafari4 : isSafari4,
        isSafari2 : isSafari2,
        isIE : isIE,
        isIE6 : isIE6,
        isIE7 : isIE7,
        isIE8 : isIE8,
        isGecko : isGecko,
        isGecko2 : isGecko2,
        isGecko3 : isGecko3,
        isBorderBox : isBorderBox,
        /**
         * True 判断操作平台是否为 Linux.
         */
        isLinux : isLinux,
        /**
         * True 判断操作平台是否为 Windows.
         */
        isWindows : isWindows,
        /**
         * True 判断操作平台是否为 Mac OS.
         */
        isMac : isMac,
        /**
         * True 判断操作平台是否为 Adobe Air.
         */
        isAir : isAir,
		
		//数据类型判断
        //是否为空
        isEmpty : function(v, allowBlank){
            return v === null || v === undefined || ((coomix.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false);
        },
		//是否为数组
        isArray : function(v){
            return toString.apply(v) === '[object Array]';
        },
		//是否为对象
        isObject : function(v){
            return v && typeof v == "object";
        },

        //是否为原生的数据类型 如 字符串 数字 布尔
        isPrimitive : function(v){
            return coomix.isString(v) || coomix.isNumber(v) || coomix.isBoolean(v);
        },

        //是否为function对象
        isFunction : function(v){
            return toString.apply(v) === '[object Function]';
        },

        //是否为数字
        isNumber: function(v){
            return typeof v === 'number' && isFinite(v);
        },

        //是否为字符串
        isString: function(v){
            return typeof v === 'string';
        },

        //是否为布尔型
        isBoolean: function(v){
            return typeof v === 'boolean';
        },

        //是否为undefined
        isDefined: function(v){
            return typeof v !== 'undefined';
        },
		
		
		//公用函数
		
		//把o中没有的但c中有的全部属性复制给o
		applyIf : function(o, c){
            if(o){
                for(var p in c){
                    if(coomix.isEmpty(o[p])){
                        o[p] = c[p];
                    }
                }
            }
            return o;
        },
		
		//循环+回调
		each: function(array, fn, scope){
            if(coomix.isEmpty(array, true)){
                return;
            }
            if(!isIterable(array) || coomix.isPrimitive(array)){
                array = [array];
            }
            for(var i = 0, len = array.length; i < len; i++){
                if(fn.call(scope || array[i], array[i], i, array) === false){
                    return i;
                };
            }
        },
		
		//删除html元素,以释放内存
        removeNode : isIE ? function(){
            var d;
            return function(n){
                if(n && n.tagName != 'BODY'){
                    d = d || DOC.createElement('div');
                    d.appendChild(n);
                    d.innerHTML = '';
                }
            };
        }() : function(n){
            if(n && n.parentNode && n.tagName != 'BODY'){
                n.parentNode.removeChild(n);
            }
        },
        /** 把json格式转化成字符串参数形式
         * Takes an object and converts it to an encoded URL. e.g. coomix.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2".  Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
         * @param {Object} o
         * @param {String} pre (optional) A prefix to add to the url encoded string
         * @return {String}
         */
        urlEncode: function(o, pre){
            var undef, buf = [], key, e = encodeURIComponent;

            for(key in o){
                undef = !coomix.isDefined(o[key]);
                coomix.each(undef ? key : o[key], function(val, i){
                    buf.push("&", e(key), "=", (val != key || !undef) ? e(val) : "");
                });
            }
            if(!pre){
                buf.shift();
                pre = "";
            }
            return pre + buf.join('');
        },
		
        /**把字符串参数形式转化成json格式对象
         * Takes an encoded URL and and converts it to an object. Example: <pre><code>
		coomix.urlDecode("foo=1&bar=2"); // returns {foo: "1", bar: "2"}
		coomix.urlDecode("foo=1&bar=2&bar=3&bar=4", false); // returns {foo: "1", bar: ["2", "3", "4"]}
		</code></pre>
         * @param {String} string
         * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
         * @return {Object} A literal with members
         */
        urlDecode : function(string, overwrite){
            var obj = {},
                pairs = string.split('&'),
                d = decodeURIComponent,
                name,
                value;
            coomix.each(pairs, function(pair) {
                pair = pair.split('=');
                name = d(pair[0]);
                value = d(pair[1]);
                obj[name] = overwrite || !obj[name] ? value :
                            [].concat(obj[name]).concat(value);
            });
            return obj;
        },

        /** 参数追加
         * Appends content to the query string of a URL, which handles logic for whether to place
         * a question mark or ampersand.
         * @param {String} url The url to append to.
         * @@param {String} s The content to append to the url.
         * @return (String) The appended string
         */
        urlAppend : function(url, s){
            if(!coomix.isEmpty(s)){
                return url + (url.indexOf('?') === -1 ? '?' : '&') + s;
            }
            return url;
        },
		
        /** 把复合类型的数据转化成数组
         * Converts any iterable (numeric indices and a length property) into a true array
         * Don't use this on strings. IE doesn't support "abc"[0] which this implementation depends on.
         * For strings, use this instead: "abc".match(/./g) => [a,b,c];
         * @param {Iterable} the iterable object to be turned into a true Array.
         * @return (Array) array
         */
        toArray : function(){
            return isIE ?
                function(a, i, j, res){
                    res = [];
                    coomix.each(a, function(v) {
                        res.push(v);
                    });
                    return res.slice(i || 0, j || res.length);
                } :
                function(a, i, j){
                    return Array.prototype.slice.call(a, i || 0, j || a.length);
                }
        }(),
		
        /**
         * Return the dom node for the passed String (id), dom node, or coomix.Element.
         * Here are some examples:
         * <pre><code>
		// gets dom node based on id
		var elDom = coomix.getDom('elId');
		// gets dom node based on the dom node
		var elDom1 = coomix.getDom(elDom);
         * </code></pre>
         * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc)
         * when this method is called to be successful.
         * @param {Mixed} el
         * @return HTMLElement
         */
        getDom : function(el){//目前只支持ID和node节点的查找
            if(!el || !DOC){
                return null;
            }
			//var dom = typeof el == "string" ? DOC.getElementById(el) : el;
            //return el.dom ? el.dom : (coomix.isString(el) ? DOC.getElementById(el) : el);
            return coomix.isString(el) ? DOC.getElementById(el) : el;
        },
		
		//命名空间创建
        namespace : function(){
            var o, d;
            coomix.each(arguments, function(v) {
                d = v.split(".");
                o = window[d[0]] = window[d[0]] || {};
                coomix.each(d.slice(1), function(v2){
                    o = o[v2] = o[v2] || {};
                });
            });
            return o;
        }
	  });
	coomix.ns = coomix.namespace;

})();

//创建命名空间
coomix.ns("coomix", "coomix.util", "coomix.lib");

/**
 * json的处理函数
 * parse函数把json字符串转换成对象
 * toJSONString把对象转换成json字符串(包括普通对象和json对象)
 * @example <pre>var json = coomix.json.parse(respontText);</pre>
 */
coomix.json = {
	parse : function(data)
	{
		if(typeof(data) != "object")
		{
			data = eval('(' + data + ')');
		}
		return data;
	},
	//把key values数组的方式转换成标准的json方式
	toNormalJson : function(data){
		  if(typeof(data) == "string"){
			data = data.toJson();
		  }

		  var keys = data.key;//{"id":0,"uid":1,"cuname":2}
		  var values = data.values || [];
		  var newdata = [];
		  for(var i =0; i<values.length; i++){
			var value = values[i];//[1,44765,"zhengdz"]
			var tmpjson = {};
			for(var key in keys){
				tmpjson[key] = value[keys[key]];//不能使用value[keys.key]
			}
			newdata.push(tmpjson);//[{"id":1,"uid":44765,"cuname":"zhengdz"}]
		  }
		  return newdata;
	},
	toJSONString : function(obj)
	{
		switch(typeof(obj))
		{
			case "object" :
			{
				var result = [];
				if(obj instanceof Array)
				{
					var len = obj.length;
					for(var i = 0; i < len; i++)
					{
						result.push(coomix.json.toJSONString(obj[i]));
					}
					return "[" + result.toString(",") + "]";
				}
				else if(obj instanceof RegExp)
				{
					return obj.toString();
				}
				else
				{
					for(var attribute in obj)
					{
						result.push(attribute + ":" + coomix.json.toJSONString(obj[attribute]));
					}
					return "{" + result.join(",") + "}";
				}
			}
			case "function":
			{
				return "function(){}";
			}
			case "number":
			{
				return obj.toString();
			}
			case "boolean":
			{
				return obj.toString();
			}
			case "string":
			{
				return "\"" + obj.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g,function(a){return ("\n" == a) ? "\\n":("\r" == a) ? "\\r":("\t" == a) ? "\\t":"";}) + "\"";
			}
			default:
			{
				return obj.toString();
			}
		}
	}
};

/**
 * 在DOM加载完成后马上执行函数的方法
 * @example <pre>coomix.ready(fn);</pre>
 */
(function (doc, win) {
    var isReady = 0,
        isBind = 0,
        fns = [],
        testEl = doc.createElement('p'),
        bindReady,
        init;

        coomix.ready = function(fn){
            bindReady(fn);

            if (isReady) {
                fn();
            } else {
                fns.push(fn);
            }
        };

        bindReady = function (){
            if(isBind) return;
            isBind = 1;

            // Catch cases where domReady is called after the browser event has already occurred.
            // readyState: "uninitalized"、"loading"、"interactive"、"complete" 、"loaded"
            if(doc.readyState === "complete") {
                init();
            } else if (doc.addEventListener) {
                doc.addEventListener("DOMContentLoaded", function () {
                    doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
                    init();
                }, false);
                win.addEventListener("onload", init, false);
            } else if(doc.attachEvent) {
                // In IE, ensure firing before onload, maybe late but safe also for iframes.
                doc.attachEvent("onreadystatechange", function() {
                    if (doc.readyState === "complete") {
                        doc.detachEvent("onreadystatechange", arguments.callee);
                        init();
                    }
                });
                win.attachEvent("onload", init);

                // If IE and not a frame, continually check to see if the document is ready.
                if(testEl.doScroll && win == win.top){
                    doScrollCheck();
                }
            }
        };

        // Process items when the DOM is ready.
        init = function () {
            isReady = 1;

            // Make sure body exists, at least, in case IE gets a little overzealous.
            // This is taked directly from jQuery's implementation.
            if (!doc.body) {
                setTimeout(init, 10);
                return;
            }

            for (var i = 0, l = fns.length; i < l; i++) {
                fns[i]();
            }
            fns = [];
        };

        function doScrollCheck() {
            if(isReady) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                testEl.doScroll('left');
            } catch (e) {
                setTimeout(doScrollCheck, 10);
                return;
            }

            init();
        }

})(document, window);

/**
 * cookie 设置读取方法
 */
coomix.cookie = {
		set : function(name,value,days,path,domain,secure)
		{
			var days = days || 100;
			var path = path || "/";
			var domain = domain || "";
			var secure = secure || "";
		    var exp  = new Date();
		    exp.setTime(exp.getTime() + days*24*60*60*1000);
		    document.cookie = name + "="+ escape (value)
		    + ";expires=" + exp.toGMTString()
		    + ";path="+ path
		    + (domain == "" ? "" : ("; domain=" + domain))
		    + (secure ? "; secure" : "");
		},
		get : function(name)
		{
			var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
			if(arr != null)
				return unescape(arr[2]);
			return null;
		},
		del : function(name)
		{
			var exp = new Date();
		    exp.setTime(exp.getTime() - 1);
		    var cval=this.get(name);
		    if(cval!=null)
		    	document.cookie= name + "="+cval+";expires="+exp.toGMTString();
		}
	};

/**
 * 对String原形的扩展
 */
coomix.extend(String.prototype,{
	trim : function () 
	{
	    return this.replace(/(^\s*)|(\s*$)/g, "");
	},
	tojson : function()
	{
		if(this==""){
			return eval('({})');
		}
		return eval('(' + this + ')');
	},
	toJson : function()
	{
		if(this==""){
			return eval('({})');
		}
		return eval('(' + this + ')');
	},
	text : function()
	{
		return this.replace(/<[^>]*>/g,"");	
	},
	random : function()
	{
		var arr = this.toArray();
		return arr[Math.floor(Math.random() * arr.length)] || null;
	},
	clean : function()
	{
		return this.replace(/\s{2,}/g, ' ').trim();
	},
	contains : function (string, s) 
	{
	    return (s) ? (s + this + s).indexOf(s + string + s) > -1 : this.indexOf(string) > -1;
	},
	escape : function () 
	{
		return this.replace(/('|\\)/g, "\\$1");
	}
});

/**
 * 对Number原形的扩展
 */
coomix.extend(Number.prototype,{
	NaN0 : function() { return isNaN(this)? 0: this; }
});

/**
 * 提供url常用操作功能
 * random 在url后面加入随机数参数
 * getAttribe 获得url中的参数值
 * replaceAttribe 替换url中的参数值
 * addAttribe 添加参数
 * getAction 获得url中action的名字(后缀可变)
 * location url跳转
 */
coomix.url = {
	random : function(url)
	{
		if (url.indexOf ("?") > 0)
		{
			url = url + "&random=" + new Date().getTime();
		}
		else
		{
			url = url + "?random=" + new Date().getTime();
		}
		return url;
	},
	getAttribe : function(type,url)
	{
		var url = url || location.href;
		var urltemp = url.split(type + "=")[1];
		if(!urltemp) return "";
		if(urltemp.indexOf("&") == -1) 
		{
			return urltemp;
		}
		else
		{
			return urltemp.split("&")[0];
		}
	},
	replaceAttribe : function(type,value,url)
	{
		var url = url || location.href;
		
		var oReg = new RegExp(type + "=([^&]+)?","g");
		
		url= url.replace(oReg, type + "=" + value);
		return url;
	},
	addAttribe : function(type,value,url)
	{
		var url = url || location.href;
		if(url.indexOf ("?") == -1)
		{
			return (url + "?" + type + "=" + value);
		}
		else
		{
			return (url + "&" + type + "=" + value);
		}
	},
	getAction : function(url,action)
	{
		var url = url || location.href;
		var action = action || ".action";
		var temp = url.split(action)[0];
		return temp.substring(temp.lastIndexOf("/")+1,temp.length);
	},
	location : function(url,message)
	{
		var url = url || location.href;
		if(!message)
		{
			window.location = url;
			return false; 
		}
		if(confirm(message))
		{
			window.location = url;
		}
		return false; 
	}
};

/**
 * 根据id快速获取dom对象的方法,直接用$方便使用和符合其它框架的习惯
 * @param id 字符串类型
 * @return DOM element
 */
coomix.$ = function(id)
{
  return document.getElementById(id);
};

/**
 * 在不确定传入id还是obj类型时快速获取dom对象的方法,用$$方便使用和记忆
 * @param el 元素id或对象
 * @return DOM element
 */
coomix.$$ = function(el)
{
  var obj = el;
	if(typeof(el) == "string")
	{
		obj = document.getElementById(el);
	}
	return obj;
};

/**
 * 根据id快速获取dom对象的方法
 * @param id 字符串类型
 * @return DOM element
 */
coomix.$id = function(id)
{
  return document.getElementById(id);
};

/**
 * 根据name快速获取dom对象的方法
 * @param name 字符串类型
 * @return DOM elements
 */
coomix.$name = function(name)
{
  return document.getElementsByName(name);
};

/**
 * 在不确定传入id还是obj类型时快速获取dom对象的方法
 * @param el 元素id或对象
 * @return DOM element
 */
coomix.$obj = function(el)
{
	var obj = el;
	if(typeof(el) == "string")
	{
		obj = document.getElementById(el);
	}
	return obj;
};

/**
 * 获取元素下面所有传入类型的对象.
 * @param tag 标签名称
 * @param el 元素id或对象,为空或不存在则默认为document
 * @example
 获取id为testTag的div下所有li对象为：coomix.$tag("li","testTag");
 获取所有li对象为：coomix.$tag("li");
 */
coomix.$tag = function(tag,el)
{
	var el = coomix.$obj(el) || document;
	return el.getElementsByTagName(tag);
};

/**
 * 获取元素的类型名称(如div span)
 */
coomix.$tagName = function(el)
{
	return coomix.$obj(el).tagName.toLowerCase();
};

/**
 * 获取iframe的contentWindow对象
 */
coomix.$F = function(el)
{
	if(!coomix.$obj(el) || coomix.$tagName(el) != "iframe")
	{
		return null;
	}
	return coomix.$obj(el).contentWindow;
};

/**
 * 取得某个范围内的随机数
 */
coomix.$random = function(min, max)
{
	return Math.floor(Math.random() * (max - min + 1) + min);
};

/**
 * 获得当前时间
 */
coomix.$time = function()
{
	return new Date().getTime();
};

/**
 * 返回document.body
 */
coomix.$body = function()
{
	return document.body;
};

/**
 * 获取元素的innerHTML内容
 * @param el 元素id或对象,默认为document.body
 */
coomix.$html = function(el)
{
	var obj = coomix.$obj(el)|| document.body;
	return 	obj.innerHTML;
};

/**
 * 获取head
 */
coomix.$head = function()
{
	return 	document.getElementsByTagName('head')[0];
};

/**
 * 获取元素的文本内容
 * @param el 元素id或对象
 */
coomix.$text = function(el)
{
	var obj = coomix.$obj(el);
	return 	obj.textContent || obj.innerText;
};

/**
 * 创建元素
 * coomix.$create("div")返回一个未绑定到DOM上的div对象
 */
coomix.$create = function(tag)
{
	return document.createElement(tag);
};

/**
 * 添加元素
 * @param el 要添加子元素的父元素
 * @param 要添加的子元素
 */
coomix.$append = function(el,child)
{
	coomix.$obj(el).appendChild(coomix.$obj(child));
};

/**
 * 删除元素对应的class
 */
coomix.$removeClass = function(className,el)
{
	coomix.$obj(el).className = coomix.$obj(el).className.replace(new RegExp("( ?|^)" + className + "\\b"), "");
};

/**
 * 判断元素是否有该class
 */
coomix.$hasClass = function(className,el)
{
	var oReg = new RegExp("( ?|^)" + className + "\\b");
	return oReg.test(coomix.$obj(el).className);
};

/**
 * 判断元素是否有该class
 */
coomix.$addClass = function(className,el)
{
	var el = coomix.$obj(el);
	if(coomix.$hasClass(className,el))
	{
		return;
	}
	else
	{
		el.className = el.className + " " + className;
	}
};

/**
 * 删除元素下对应标签元素所有对应的样式
 */
coomix.$removeTagClass = function(className,tag,el)
{
	var els = coomix.$tag(tag,el);
	var len = els.length;
	for(var i = 0; i < len; i++)
	{
		coomix.$removeClass(className,els[i]);
	}
};

/**
 * 获取元素下对应标签下对应样式的所有元素
 */
coomix.$getTagClassElements = function(className,tag,el)
{
	var els = coomix.$tag(tag,el);
	var result = [];
	var len = els.length;
	for(var i = 0; i < len; i++)
	{
		if(coomix.$hasClass(className,els[i]))
		{
			result[result.length] = els[i];
		}
	}
	return result;
};

/**
 * 隐藏元素，可以传入id或对象
 */
coomix.$hide = function(el)
{
	coomix.$obj(el).style.display = "none";
};

/**
 * 显示元素，可以传入id或对象
 */
coomix.$show = function(el)
{
	coomix.$obj(el).style.display = "";
};

/**
 * 此元素下所有对应标签的元素
 */
coomix.$hiddenTag = function(tag,el)
{
	var els = coomix.$tag(tag,el);
	var len = els.length;
	for(var i = 0; i < len; i++)
	{
		els[i].style.display = "none";
	}
};

/**
 * 获取非position定位的元素top属性值
 */
coomix.$top = function(el)
{
	var obj = coomix.$obj(el);
	if(coomix.browser.msie)
	{
		var top = 0;
	}
	else
	{
		var top = 2;
	}
	while(obj.offsetParent)
	{
		//obj.currentStyle.borderTopWidth ie6下可能返回的不是数字类型的值
		top += obj.offsetTop + (obj.currentStyle?(parseInt(obj.currentStyle.borderTopWidth)).NaN0():0);
		obj = obj.offsetParent;
	}
	top += obj.offsetTop + (obj.currentStyle?(parseInt(obj.currentStyle.borderTopWidth)).NaN0():0);
	
	return top;
};

/**
 * 获取非position定位的元素left属性值
 */
coomix.$left = function(el)
{
	var obj = coomix.$obj(el);
	if(coomix.browser.msie)
	{
		var left = -2;
	}
	else
	{
		var left = 0;
	}
	while(obj.offsetParent)
	{
		left += obj.offsetLeft + (obj.currentStyle?(parseInt(obj.currentStyle.borderLeftWidth)).NaN0():0);
		obj = obj.offsetParent;
	}
	left += obj.offsetLeft + (obj.currentStyle?(parseInt(obj.currentStyle.borderLeftWidth)).NaN0():0);
	
	return left;
};

/**
 * 动态插入脚本并执行
 * @param scriptStr
 * @param el dom元素对象或ID 可以不传入
 * @exsample coomix.$script("<script>alert(2);<\/script>");
 */
coomix.$script = function(scriptStr,el)
{
	var el = coomix.$obj(el);
	if(!el){
		var div = coomix.$create("div");
		div.style.display = "none";
		coomix.$append(document.body,div);
		el = div;
	}
	if(coomix.browser.msie){
		scriptStr = '<div style="display:none">ie</div>' + scriptStr;
		//当节点被移除的时候，ie会重新解析节点内部的html，有脚本则会执行相关的脚本，script要加上defer属性
		scriptStr = scriptStr.replace(/<script([^>]*)>/gi,'<script$1 defer>');
		el.innerHTML = scriptStr;
		el.removeChild(el.firstChild);
	}else{
		var el_next = el.nextSibling;
		var el_parent = el.parentNode;
		el_parent.removeChild(el);
		el.innerHTML = scriptStr;
		if (el_next) {
			el_parent.insertBefore(el, el_next);
		}else {
			el_parent.appendChild(el);
		}
	}
};

/**
 * 插入html代码，解决火狐下不能直接插入html字符串的问题
 * @param where 插入相对el对象的位置：before 插入到之前，top插入到最前面，bottom插入到最后，after插入到之后
 * @param el 插入的相对元素 默认为document.body
 * @param html 插入的html字符串
 * @exsample coomix.$insert("top","testDiv","<div>test coomix.$insert html</div>");
 */
coomix.$insert = function(where, el, html)
{
	var el = coomix.$obj(el) || document.body;
	where = where.toLowerCase();   
	if(el.insertAdjacentHTML)
	{
	    switch(where)
	    {   
	        case "before":   
	            el.insertAdjacentHTML('beforeBegin', html);   
	            return el.previousSibling;
	            break;
	        case "top":   
	            el.insertAdjacentHTML('afterBegin', html);   
	            return el.firstChild;
	            break;
	        case "bottom":   
	            el.insertAdjacentHTML('beforeEnd', html);   
	            return el.lastChild;
	            break; 
	        case "after":   
	            el.insertAdjacentHTML('afterEnd', html);   
	            return el.nextSibling;
	            break;
	    }
	    throw 'Illegal insertion point -> "' + where + '"';   
	}
	
	var range = el.ownerDocument.createRange();   
    var frag;
    switch(where)
    {   
         case "before":   
            range.setStartBefore(el);   
            frag = range.createContextualFragment(html);   
            el.parentNode.insertBefore(frag, el);   
            return el.previousSibling;
            break;
         case "top":   
            if(el.firstChild)
            {   
                range.setStartBefore(el.firstChild);   
                frag = range.createContextualFragment(html);   
                el.insertBefore(frag, el.firstChild);   
                return el.firstChild;
            }else
            {   
                el.innerHTML = html;   
                return el.firstChild;   
            }
            break;
        case "bottom":   
            if(el.lastChild)
            {   
                range.setStartAfter(el.lastChild);   
                frag = range.createContextualFragment(html);   
                el.appendChild(frag);   
                return el.lastChild;   
            }
            else
            {   
                el.innerHTML = html;   
                return el.lastChild;   
            }
            break;
        case "after":   
            range.setStartAfter(el);   
            frag = range.createContextualFragment(html);   
            el.parentNode.insertBefore(frag, el.nextSibling);   
            return el.nextSibling; 
            break;  
        }   
        throw 'Illegal insertion point -> "' + where + '"';
};


/**
 * 根据class名称，选择dom对象，返回值为节点对象集合
 * @param name 必需参数,标签的class名
 * @param root 选填参数,父标签(可以是id名或者节点对象)
 * @param tag  选填参数,标签名(例如div,p,li)
 */
coomix.dom.getElementsByClass=function(name,root,tag){
	root= coomix.$obj(root);
	tag = tag || "*";
	var oEle=coomix.$tagName(tag);
	oArr=[];
	for(var i=0,iLenA=oEle.length;i<iLenA;i++){
		for(var j=0,sNames=oEle[i].className.split(" "),iLenB=sNames.length;j<iLenB;j++){
			if(sNames[j]==name){
				oArr.push(oEle[i]);
				break;					
				}
			}
		}
		return oArr;
	};
/**
 * 获取下一个节点方法
 * @param node 必需参数(可以是id名或者节点对象)
 */
coomix.dom.getNextNode = function(node){
	node = coomix.$obj(onde);
	if(!node.nextSibling) return null;
	var nextNode = node.nextSibling;
	if(nextNode.nodeType==1){
		return nextNode;
		}else{
	while(nextNode = nextNode.nextSibling){
			if(nextNode.nodeType==1)
			break;
		}
	}
return nextNode;
};


/**
 * ajax框架类，提供五个对外接口.
 * 一般情况下都是异步请求(同步用ajax没有意义)asynchronous可以不用传入
 * 第三个参数extend为callbackFunction的扩展参数,可以不传入，后面有其他参数同时没有扩展参数可以传入null
 * coomix.ajax.get(url,callbackFunction,extend,asynchronous)
 * coomix.ajax.post(url,callbackFunction,formElement,extend,encode,asynchronous)
 * coomix.ajax.postText(url,callbackFunction,formElement,extend,asynchronous)
 * coomix.ajax.postUnencode(url,callbackFunction,formElement,extend,asynchronous)
 * coomix.ajax.jsonp(url,callbackFunction,responseName,extend)
 */
coomix.ajax = function()
{
	this.version = "1.0";
};

/**
 * 创建XMLHttpRequest工厂类
 */
coomix.ajax.createRequest = function()
{
	var objXMLHttp = null;

	if (window.XMLHttpRequest)
	{
		objXMLHttp = new XMLHttpRequest();
	    
		if (objXMLHttp.overrideMimeType)
		{
			objXMLHttp.overrideMimeType('text/xml');
		}
	}
	else
	{
	    var MSXML = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0'];
	    
	    for(var n = 0; n < MSXML.length; n++)
	    {
	        try
	        {
	            objXMLHttp = new ActiveXObject(MSXML[n]);        
	            break;
	        }
	        catch(e) {}
	    }
	}
	
  	return objXMLHttp;
};

/**
 * 本域get请求
 * @param url 请求相对路径
 * @param callbackFunction 回调函数
 * @param extend 回调函数扩展参数(json格式)
 * @param asynchronous 是否为异步请求，默认为true
 * @example
function testGet()
{
	var url = "ajax_test.action?type=localhost";
	coomix.ajax.get(url,getCallback,{test1:'aaa1',test2:'bbb1'});
	//coomix.ajax.get(url,function(test1,test2,responseText){alert(responseText);alert(test1);},{test1:'aaa1',test2:'bbb1'});
}
function getCallback(responseText,test1,test2)
{
	alert("getCallback responseText = " + responseText);
	alert("getCallback message = " + responseText.toJson().message);
	alert("getCallback test1 = " + test1);
}
 */
coomix.ajax.get = function(url,callbackFunction,extend,asynchronous)
{
	var http_request = coomix.ajax.createRequest();
	coomix.ajax.bindResponse (http_request,callbackFunction,extend);		
	url = coomix.url.random(url);
	asynchronous = asynchronous || true;
	http_request.open ("GET", url, asynchronous);
	
	http_request.send (null);
	
	return false;
};

/**
 * post请求
 * @param url 请求相对路径
 * @param formElement 表单对象或表单id
 * @param callbackFunction 回调函数
 * @param extend 回调函数扩展参数(json格式)
 * @param encode 编码方式text，unencode，其他，默认采用通用的两次encodeURIComponent
 * 后台解码：java.net.URLDecoder.decode(request.getParameter("name"), "UTF-8″);
 * @param asynchronous 是否为异步请求，默认为true
 * @example
function testPost()
{
	var url = "../getData?action=getPostData";
	var form = coomix.$id("post_add");
	//no extend param
	//coomix.ajax.post(url,postCallback,"post_add");
	
	//extend json object
	var id = form.id;
	//coomix.ajax.post(url,postCallback,"post_add",{test1:id,test2:'bbb3'});
	
	//extend jsonStr
	var jsonStr = "{test1:'" + id + "',test2:'bbb3'}"
	var ext = jsonStr.toJson();
	//var ext = eval('(' + json + ')');
	coomix.ajax.post(url,postCallback,"post_add",ext);
	
}
function postCallback(responseText,test1,test2)
{
	//{success:true,action:'getPostData',message:'test message'}
	alert("postCallback responseText = " + responseText);
	alert("postCallback is success = " + responseText.toJson().success);
	alert("postCallback message = " + responseText.toJson().message);
	alert("postCallback test1 = " + test1);
	alert("postCallback test2 = " + test2);
}
<form action="" id="post_add" name="post_add" method="post" onsubmit="return false;">
		<textarea name="message" id="message">test message 测试中文</textarea>
		<input type="button" id="subBtn" value="submit" onclick="testPost()" />
</form>
 */
coomix.ajax.post = function(url,callbackFunction,formElement,extend,encode,asynchronous)
{
	var http_request = coomix.ajax.createRequest();
	
	coomix.ajax.bindResponse(http_request,callbackFunction,extend);		
	url = coomix.url.random(url);
	asynchronous = asynchronous || true;
	formElement = coomix.$obj(formElement);
	//获取表单内容字符串，转换比较多，需要时间比较久
	var requireString = coomix.ajax.parseParameteres(formElement,encode);
	//获取字符串后再打开链接
	http_request.open("POST", url, asynchronous);
	
	http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	http_request.setRequestHeader("encoding","utf-8");
	http_request.setRequestHeader("Content-length", requireString.length);
	//在win2000下的ie6.0会导致很慢
	//jquery mootools ext中都没有此项设置,prototype-1.6下说明为了兼容低版本的Mozilla浏览器才设置的
	//http_request.setRequestHeader("Connection","close");
	
	//Mozilla浏览器post方法不能用send(null)没有内容必须用send("")
	if(requireString == null){requireString = "";}
	http_request.send(requireString);
	
	return false;
};

/**
 * 文本形式post请求(去掉换行符和html标签)
 */
coomix.ajax.postText = function(url,callbackFunction,formElement,extend,asynchronous)
{
	coomix.ajax.post(url,callbackFunction,formElement,extend,"text",asynchronous);
};

/**
 * 不进行编码，直接提交表单内容
 */
coomix.ajax.postUnencode = function(url,callbackFunction,formElement,extend,asynchronous)
{
	coomix.ajax.post(url,callbackFunction,formElement,extend,"unencode",asynchronous);
};

/**
 * 跨域请求
 * @param url 请求路径,跨域要完整的路径，本域可以是相对路径
 * @param callbackFunction 回调函数
 * @param responseName 服务端返回的变量名称,会把值自动附加到url参数中，后台可以获取到
 * @param extend 回调函数扩展参数(json格式)
 * @example
function testJsonp()
{
	var url = "http://zhengdz.iap111.com:8080/coomix/coomix/ajax_test.action?type=remote";
	coomix.ajax.jsonp(url,jsonpCallback,"remote_request",{test1:'aaa2',test2:'bbb2'});
}
function jsonpCallback(responseText,test1,test2)
{
	alert("jsonpCallback responseText = " + responseText);
	alert("jsonpCallback message = " + responseText.toJson().message);
	alert("jsonpCallback test1 = " + test1);
}
 */
coomix.ajax.jsonp = function(url,callbackFunction,responseName,extend)
{
	var script = document.createElement("script");
	script.id = "coomix_jsonp_" + responseName;
	
    if(script.addEventListener)
    {
		script.addEventListener("load", function(){
			coomix.ajax.jsonp.callbackHandle(callbackFunction,responseName,extend);
			}, false);
    }   
	else if(script.attachEvent)
	{
		script.attachEvent("onreadystatechange",function(){
			var target = window.event.srcElement;
			if(target.readyState == "loaded")
			{
				coomix.ajax.jsonp.callbackHandle(callbackFunction,responseName,extend);
			}
			});
	}
	//通过url参数传递给后台，后台通过request获取responseName参数值获得传递过去的变量名
	if(responseName)
	{
		url = coomix.url.addAttribe("responseName",responseName,url);
	}
	url = coomix.url.random(url);
	script.src = url;
	coomix.$head().appendChild(script);
};

/**
 * 跨域请求回调处理函数,在script脚本onload完成后执行
 * @param callbackFunction 回调函数
 * @param extend 回调函数扩展参数(json格式)
 * @param responseName 服务端返回的变量名称
 */
coomix.ajax.jsonp.callbackHandle = function(callbackFunction,responseName,extend)
{
 	try
	{
		var responseText = eval(responseName);
		//非字符串类型转换为json字符串类型
		if(typeof(responseText) == "object")
		{
			responseText = coomix.json.toJSONString(responseText);
		}
		
		callbackFunction["responseText"] = responseText;
		var args = [];
		args.push(responseText);
		if(typeof(extend) == "object" && extend !== null)
		{
			for (var property in extend)
			{
				//绑定property,可以通过函数本身调用
				callbackFunction[property] = extend[property];
				//把参数值按照顺序放入到数组中，通过apply传入
				args.push(extend[property]);
			}
		}
		//动态调用函数，把参数值数组传入
		callbackFunction.apply(this,args);
		//移除本次请求的script脚本，避免脚本不断增加
		coomix.$head().removeChild(coomix.$id("coomix_jsonp_" + responseName));
	}
	catch(e)
	{
		//alert("实际错误消息为：" + e.message + "\n错误类型字符串为：" + e.name);
	}
};

/**
 * escape字符串，并对特殊符号作处理
 * @param str 需要处理的字符串
 * @param encode 编码方式：unencode,text,other
 */
coomix.ajax.encode = function(str,encode)
{
	//不传入编码类型则默认编码
	if(typeof(encode) == "undefined"){encode = "encode";}
	//str为空或不用编码则直接返回
	if (str == null || str == "" || encode=="unencode")
	{
		return str;
	}
	var value = "";
	//value编码采用和jquery一样的处理方式
	//后台解码：java.net.URLDecoder.decode(request.getParameter("name"), "UTF-8″);
	if(encode == "text")
	{
		value = str.replace(/\n|\r|\r\n/g,"");//去掉换行符号
		value = value.replace(/<\/?.+?>/g,"");//去掉HTML标签
		value = encodeURIComponent(encodeURIComponent(value)).replace(/%20/g, "+");
	}
	else
	{
		value = encodeURIComponent(encodeURIComponent(str)).replace(/%20/g, "+");
	}
	return value;
};

/**
 * 获取表单内容字符串,表单只有input select textarea 三种类型
 * @param formElement 表单对象或id
 */
coomix.ajax.parseParameteres = function(formElement,encode)
{
	formElement = coomix.$obj(formElement);
	var rs = "";
	rs += coomix.ajax.getValue(formElement.getElementsByTagName("input"),"input",encode);
	rs += coomix.ajax.getValue(formElement.getElementsByTagName("select"),"select",encode);
	rs += coomix.ajax.getValue(formElement.getElementsByTagName("textarea"),"textarea",encode);
	return rs;
};

/**
 * 获取单个表单元素的内容
 * @param elements 表单元素对象
 * @param type 表单元素类型
 */
coomix.ajax.getValue = function(elements,type,encode)
{
	var len = elements.length;
	if(len == 0)return "";
	var s = "";
	
	if(type == "input")
	{
		for (var i = 0; i < len; i++)
		{
			var obj = elements[i];
			
			if (obj.type == "hidden")
			{
				s += obj.name + "=" + coomix.ajax.encode(obj.value,encode) + "&";
			}
			else if (obj.type == "text")
			{
				s += obj.name + "=" + coomix.ajax.encode(obj.value,encode) + "&";
			}
			else if (obj.type == "password")
			{
				s += obj.name + "=" + coomix.ajax.encode(obj.value,encode) + "&";
			}
			else if (obj.type == "checkbox")
			{
				if (obj.checked)
				{
					s += obj.name + "=" + coomix.ajax.encode(obj.value,encode) + "&";
				}
			}
			else if (obj.type == "radio")
			{
				if (obj.checked)
				{
					s += obj.name + "=" + coomix.ajax.encode(obj.value,encode) + "&";
				}
			}
		}
	}
	else if(type == "textarea")
	{
		for (var i = 0; i < len; i++)
		{
			var obj = elements[i];
			
			s += obj.name + "=" + coomix.ajax.encode(obj.value,encode) + "&";
		}
	}
	else if(type == "select")
	{
		for (var i = 0; i < len; i++)
		{
			var obj = elements[i];
			
			if (obj.type == "select")
			{
				if (obj.selectedIndex > -1)
					s += obj.name + "=" + coomix.ajax.encode(obj.options[obj.selectedIndex].value,encode) + "&";
			}
			else if (obj.type == "select-one")
			{
				if (obj.selectedIndex > -1)
					s += obj.name + "=" + coomix.ajax.encode(obj.options[obj.selectedIndex].value,encode) + "&";
			}
		}
	}
	return s;
};

/**
 * 绑定ajax请求回调函数，属于内部函数
 */
coomix.ajax.bindResponse = function(http_request,callbackFunction,extend)
{
	if(typeof(callbackFunction) != "function")
	{
		alert("请传入回调函数!");
		return false;
	}
	var responseText = "";
	var isTiemout = false;
	//设定5秒后请求超时
	setTimeout(function(){isTimeout = true;},5000);
	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4 && !isTiemout)
		{
			if (http_request.status == 200)
			{
				responseText = http_request.responseText;
				try
				{
					//绑定property,可以通过函数本身调用
					callbackFunction["responseText"] = responseText;
					var args = [];
					//把responseText放入第一个位置，通过apply传入
					args.push(responseText);
					if(typeof(extend) == "object" && extend !== null)
					{
						for (var property in extend)
						{
							//绑定property,可以通过函数本身调用
							callbackFunction[property] = extend[property];
							//把参数值按照顺序放入到数组中，通过apply传入
							args.push(extend[property]);
						}
					}
					//动态调用函数，把参数值数组传入
					callbackFunction.apply(this,args);
					//eval(callbackFunction);
					
					//为避免内存泄漏，清理文档
					try{http_request = null;}catch(e){}
				}
				catch(e)
				{
					alert("实际错误消息为：" + e.message + "\n错误类型字符串为：" + e.name);
				}
			}
			else
			{
				var status = http_request.status;
				switch (status) 
				{
					case 403:
						alert("你请求的页面禁止访问!");
						break;
					case 404:
						alert("你请求的页面不存在!");
						break;	
					case 500:
						alert("你请求的页面服务器内部错误!");
						break;
					case 502:
						alert("Web服务器收到无效的响应!");
						break;
					case 503:
						alert("服务器繁忙，请稍后再试!");
						break;
					default:
						alert("你请求的页面遇到问题，操作失败!错误代码:" + status);
						break;
				}
			}
		}
		
	};
};

/**
 * 事件公共方法，解决一些兼容性问题
 */
coomix.event = function(e)
{
	var e = e || window.event;
	return e;
};

/**
 * 格式化事件
 */
coomix.event.format = function(e) 
{
	var e = e || window.event;
	try
	{
		if(!e.pageX && e.clientX)//firefox3 nonsupport pageX
		{
			e.pageX = e.clientX + document.body.scrollLeft;
			e.pageY = e.clientY + document.documentElement.scrollTop;
		}
	}
	catch(e){}
	
	if(window.event)
	{
		e.charCode = (e.type == "keypress") ? e.keyCode : 0;
		e.eventPhase = 2;
		e.isChar = (e.charCode > 0);
		e.preventDefault = function ()
		{
			this.returnValue = false;
		};
		
		if(e.type == "mouseout")
		{
			e.relatedTarget = e.toElement;
		}
		else if(e.type == "mouseover")
		{
			e.relatedTarget = e.formElement;
		}
		
		e.stopPropagation = function ()
		{
			this.cancelBubble = true;
		};
		
		e.target = e.srcElement;
		e.time   = (new Date()).getTime();
	}
	
	try
	{
		if (e.target.nodeType == 3)
		{// defeat Safari bug
			e.target = e.target.parentNode;
		}
		//如果不存在keyCode属性，同时存在which属性则赋值,因为该属性为只读属性(has only a getter)
		if(!e.keyCode && e.which)
		{
			e.keyCode = e.which;
		}
	}
	catch(e){}
	
	return e;
};

/**
 * 添加事件监听
 */
coomix.event.add = function(el,EventType,callback)
{
	var obj = coomix.$obj(el);
	
	if(obj.addEventListener)
	{
		obj.addEventListener(EventType,callback,false);
	}
	else if(obj.attachEvent)
	{
		obj.attachEvent('on'+EventType,callback);
	} 
	else
	{
		obj['on'+EventType] = callback;
	}
};

/**
 * 删除事件监听
 */
coomix.event.remove = function(el,EventType,callback)
{
	var obj = coomix.$obj(el);
	
	if(obj.removeEventListener)
	{
		obj.removeEventListener(EventType,callback,false);
	} 
	else if(obj.detachEvent)
	{
		obj.detachEvent('on'+EventType,callback);
	} 
	else
	{
		obj['on'+EventType] = callback;
	}
};

/**
 * 停止事件
 */
coomix.event.stop = function(e) 
{
    coomix.event.format(e).stopPropagation();
};

/**
 * 取消事件
 */
coomix.event.cancel = function(e) 
{
    coomix.event.format(e).preventDefault();
};

/**
 * 获取页面x坐标，即left
 */
coomix.event.pageX = function(e)
{
	return coomix.event.format(e).pageX;
};

/**
 * 获取页面y坐标，即top
 */
coomix.event.pageY = function(e)
{
	return coomix.event.format(e).pageY;
};

/**
 * 获取触发事件的元素对象
 */
coomix.event.element = function(e)
{
	return coomix.event.format(e).target;
};

/**
 * 获取键盘键值
 */
coomix.event.keyCode = function(e)
{
	return coomix.event.format(e).keyCode;	
};

